package com.ilemon.upload.api.controller;


import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.RequestContext;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping(value = "/upload")
public class UploadController {


    //定义日期格式
    SimpleDateFormat sdf = new SimpleDateFormat("/YYYY/MM/dd/");

    /**
     * 跨服务器文件上传
     *
     * @return
     */
    @RequestMapping("/fileupload3")
    public String fileuoload3(MultipartFile upload) throws Exception {
        System.out.println("跨服务器文件上传...");

        // 定义上传文件服务器路径
        String path = "http://localhost:9090/uploads/";

        // 说明上传文件项
        // 获取上传文件的名称
        String filename = upload.getOriginalFilename();
        // 把文件的名称设置唯一值，uuid
        String uuid = UUID.randomUUID().toString().replace("-", "");
        filename = uuid + "_" + filename;

//        // 创建客户端的对象
//        Client client = Client.create();
//
//        // 和图片服务器进行连接
//        WebResource webResource = client.resource(path + filename);
//
//        // 上传文件
//        webResource.put(upload.getBytes());

        return "success";
    }

    /**
     * SpringMVC文件上传
     *
     * @return
     */
    @RequestMapping("/fileupload2")
    public String fileuoload2(HttpServletRequest request, MultipartFile upload) throws Exception {
        System.out.println("springmvc文件上传...");

        // 使用fileupload组件完成文件上传
        // 上传的位置
        String path = request.getSession().getServletContext().getRealPath("/uploads/");
        // 判断，该路径是否存在
        File file = new File(path);
        if (!file.exists()) {
            // 创建该文件夹
            file.mkdirs();
        }

        // 说明上传文件项
        // 获取上传文件的名称
        String filename = upload.getOriginalFilename();
        // 把文件的名称设置唯一值，uuid
        String uuid = UUID.randomUUID().toString().replace("-", "");
        filename = uuid + "_" + filename;
        // 完成文件上传
        upload.transferTo(new File(path, filename));

        return "success";
    }

    /**
     * 文件上传
     *
     * @return
     */
    @RequestMapping("/fileupload1")
    public String fileuoload1(HttpServletRequest request) throws Exception {
        System.out.println("文件上传...");

        // 使用fileupload组件完成文件上传
        // 上传的位置
        String path = request.getSession().getServletContext().getRealPath("/uploads/");
        // 判断，该路径是否存在
        File file = new File(path);
        if (!file.exists()) {
            // 创建该文件夹
            file.mkdirs();
        }

        // 解析request对象，获取上传文件项
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        // 解析request
        List<FileItem> items = upload.parseRequest((RequestContext) request);
        // 遍历
        for (FileItem item : items) {
            // 进行判断，当前item对象是否是上传文件项
            if (item.isFormField()) {
                // 说明普通表单向
            } else {
                // 说明上传文件项
                // 获取上传文件的名称
                String filename = item.getName();
                // 把文件的名称设置唯一值，uuid
                String uuid = UUID.randomUUID().toString().replace("-", "");
                filename = uuid + "_" + filename;
                // 完成文件上传
                item.write(new File(path, filename));
                // 删除临时文件
                item.delete();
            }
        }

        return "success";
    }


    /**
     * 文件上传 https://blog.csdn.net/huangjhai/article/details/104128929
     *
     * @param file
     * @param req
     * @return
     */
    @PostMapping("/upload")
    public String upload(MultipartFile file, HttpServletRequest req) {
        //获取上传的日期
        String date = sdf.format(new Date());
        //当前项目下的保存路径
        String realPath = req.getServletContext().getRealPath("/img") + date;
        //判断保存路径的文件夹是否已创建
        File folder = new File(realPath);
        if (!folder.exists())
            folder.mkdirs();
        //获取上传的文件名
        String oldName = file.getOriginalFilename();
        //保存的文件名，使用UUID类生成通用唯一识别码，避免文件名重复
        String newName = UUID.randomUUID().toString() + oldName.substring(oldName.lastIndexOf("."));
        //保存文件到项目的保存路径中
        try {
            file.transferTo(new File(folder, newName));
            //得到完整的保存路径
            String url = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + "/img" + date + newName;
            return url;

        } catch (IOException e) {
            e.printStackTrace();
        }
        return "error";
    }

    /**
     * 多文件上传 https://blog.csdn.net/huangjhai/article/details/104128929
     *
     * @param files
     * @param req
     * @return
     */
    @PostMapping("/uploads")
    public String uploads(MultipartFile[] files, HttpServletRequest req) {
        //获取上传的日期
        String date = sdf.format(new Date());
        //当前项目下的保存路径
//        String realPath = req.getServletContext().getRealPath("/img") + date;
        String realPath = getPath() + date;

        //判断保存路径的文件夹是否已创建
        File folder = new File(realPath);
        if (!folder.exists())
            folder.mkdirs();
        for (MultipartFile file : files) {
            //获取上传的文件名
            String oldName = file.getOriginalFilename();
            //保存的文件名
            String newName = UUID.randomUUID().toString() + oldName.substring(oldName.lastIndexOf("."));
            //保存文件到项目的保存路径中
            try {
                file.transferTo(new File(folder, newName));
                //得到完整的保存路径
                String url = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + "/img" + date + newName;
                System.out.println(url);
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        return "success";
    }


    /**
     * 获取用户的目录 并拼接新存储日志目录
     *
     * @return
     */
    private static String getPath() {
        // 获取用户的目录
        String property = System.getProperty("user.home");
        String replaceAll = property.replaceAll("\\\\", "/");
        String path = replaceAll + "/appUploadLog/";
        System.out.println("IndexController --getPath---------1--------\n" + path);
        return path;
    }
}
